package zhizhemodi.tech.short_term_bwork.service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import zhizhemodi.tech.short_term_bwork.entity.User;
import zhizhemodi.tech.short_term_bwork.mapper.UserMapper;

@Service
public class UserService {
    
    @Autowired
    UserMapper userMapper;

    /**
     * 查找用户
     * @param column
     * @param num
     * @param rowNum
     * @param pageNum
     * @return
     */
    public List<User> findUsers(String column, Object num, Integer rowNum, Integer pageNum) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, num);
        queryWrapper.last(" limit " + pageNum * rowNum + "," + rowNum);
        return userMapper.selectList(queryWrapper);
    }

    /**
     * 新增用户
     * @param users
     */
    public void addUserList(List<User> users) {
        List<User> uList = userMapper.selectList(null);
        Integer uId = -1;
        if(uList.size() > 0) uId = uList.get(uList.size() - 1).getUserId();
        for(User user : users) {
            if(findUsers("user_name", user.getUserName(), 1, 0).size() == 0) {
                uId+=1;
                user.setUserId(uId);
                userMapper.insert(user);
            }
        }
    }

    /**
     * 用户更新入口函数
     * @param userId
     * @param infoMap
     */
    public void updateUserList(Integer userId, Map<String, Object> infoMap) {
        User user = userMapper.selectById(userId);
        for(String key : infoMap.keySet()) {
            user = updateUser(user, key, infoMap.get(key));
        }
        userMapper.updateById(user);
    }

    /**
     * 更新用户单项信息
     * @param user
     * @param column
     * @param info
     * @return
     */
    private User updateUser(User user, String column, Object info) {
        switch(column) {
            case "userPwd": user.setUserPwd(info.toString());break;
            case "departmentId": user.setDepartmentId(Integer.valueOf(info.toString()));break;
            case "userName": user.setUserName(info.toString());break;
            case "trueName": user.setTrueName(info.toString());break;
            case "phoneNum": user.setPhoneNum(info.toString());break;
            case "email": user.setEmail(info.toString());break;
            case "updateTime": user.setUpdateTime(Timestamp.valueOf(info.toString()));break;
            case "userState": user.setUserState(Boolean.valueOf(info.toString()));break;
            default:break;
        }
        return user;
    }

    /**
     * 删除用户
     * @param userId
     */
    public void deleteUser(Integer userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        userMapper.delete(queryWrapper);
    }
}
